package org.shiro.action;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.shiro.bean.JsonResult;
import org.shiro.entity.Role;
import org.shiro.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** @author HKC */
@Api(tags = "角色接口", value = "测试角色接口数据")
@RestController
@RequestMapping("/role")
public class RoleController {
  @Autowired private RoleService roleService;

  @ApiOperation(value = "添加角色", notes = "向数据库里插入新数据")
  @PostMapping("/insert")
  @ResponseStatus(HttpStatus.CREATED)
  public JsonResult insertRole(@RequestBody Role role) {
    int res = roleService.create(role);
    if (res > 0) {
      return JsonResult.success("插入数据成功", role);
    }
    return JsonResult.failure("插入数据失败");
  }

  @ApiOperation(value = "删除数据", notes = "从数据库当中删除数据")
  @DeleteMapping("/{id}")
  public JsonResult removeRole(@PathVariable("id") Long id) {
    int res = roleService.remove(id);
    if (res > 0) {
      return JsonResult.success("删除数据成功");
    }
    return JsonResult.failure("删除数据失败");
  }

  @ApiOperation(value = "查询角色", notes = "从数据库当中获取数据")
  @GetMapping("/{id}")
  public JsonResult loadRole(@PathVariable("id") Long id) {
    Role role = roleService.load(id);
    if (role != null) {
      return JsonResult.success("获取数据成功", role);
    }
    return JsonResult.failure("获取数据失败");
  }

  @ApiOperation(value = "修改角色信息", notes = "对数据库中的数据修改")
  @PutMapping("/update")
  public JsonResult modity(@RequestBody Role role) {
    int res = roleService.modity(role);
    if (res > 0) {
      return JsonResult.success("修改数据成功", role);
    }
    return JsonResult.failure("修改数据失败");
  }

  @ApiOperation(value = "查询角色拥有的权限", notes = "按照提交数据查询角色对应的权限")
  @GetMapping("/queryMenu")
  public JsonResult queryMenu(@RequestParam("rolename") String rolename) {
    List<Role> roleList = roleService.queryMenu(rolename);
    if (roleList.isEmpty() || roleList.size() <= 0) {
      throw new IllegalArgumentException("当前数据库中没有数据");
    }
    return JsonResult.success("查询数据成功", roleList);
  }
}
